<template>
  <view>
    <map-planning
      width="100vw"
      height="100vh"
      :Config="mapData.Config"
      :startPoi="mapData.startPoi"
      :wayPoi="mapData.wayPoi"
      :endPoi="mapData.endPoi"
      :customMarker="customMarker"
      :scale="13"
    />
  </view>
</template>

<script setup lang="ts">
import $API from '@/api'
import { $modal } from '@/plugins'
import $store from '@/store'
import { ShopForMap, type DinersForMap } from '@/types/response/delivery-order'
import { onBeforeMount } from 'vue'
import { ref } from 'vue'
import MapPlanning from '@/components/map-planning/index.vue'

const mapData = ref({
  Config: {
    showMarks: true,
    lineColor: '#0606ff', //路径颜色
    lineWidth: 3 //路径宽度
  },
  startPoi: '',
  wayPoi: '',
  endPoi: ''
})
// 自定义的marker内容
const customMarker = ref<{ latitude: number; longitude: number; [key: string]: any }[]>([])
onBeforeMount(async () => {
  // 获取骑手当前位置
  const riderGeo = await $store.user.geo.refreshAndGet()
  // 请求地图渲染需要的数据
  const result = await $API.deliveryOrder.riderRoutePlanning(riderGeo)
  if (!result.success) {
    $modal.toastErrorMsg('无法获取地图渲染需要的数据')
    return
  }
  // 存储业务“顺序导航”信息
  const points: Array<ShopForMap | DinersForMap> = []
  // 添加东西到“顺序导航”，并添加对应的自定义marker
  for (let point of result.data) {
    if (point.isHasWaitFetchOrder) {
      points.push(point)
      customMarker.value.push({
        latitude: point.latitude!,
        longitude: point.longitude!,
        iconPath: '/static/image/planning/shop.svg',
        label: {
          content: point.dinersForMaps.reduce((_sum, curr) => (_sum += curr.isWaitFetch ? `#${curr.code}` : ''), `取`),
          textAlign: 'center'
        },
        callout: {
          content: `${point.shopName}`,
          display: 'ALWAYS',
          textAlign: 'center',
          bgColor: '#ff644d',
          padding: '2px'
        }
      })
    }
    points.push(...point.dinersForMaps)
  }
  // 对顺序导航进行排序
  points.sort((o1, o2) => o1.navigationSort! - o2.navigationSort!)
  // 折叠同配送
  for (let i = 1; i < points.length; i++) {
    const lastNode = points[i - 1]
    const currNode = points[i]
    if ((lastNode as DinersForMap).shopId === undefined || (currNode as DinersForMap).shopId === undefined) {
      continue
    }

    if (
      lastNode.latitude === currNode.latitude &&
      lastNode.longitude === currNode.longitude &&
      (lastNode as DinersForMap).consigneeName === (currNode as DinersForMap).consigneeName
    ) {
      // 折叠
      if ((lastNode as DinersForMap).codes == null) {
        ;(lastNode as DinersForMap).codes = [(lastNode as DinersForMap).code]
      }
      ;(lastNode as DinersForMap).codes?.push((currNode as DinersForMap).code)
      points.splice(i--, 1)
    }
  }
  // 给DinersForMap添加customMarker
  for (let point of points) {
    // 假设为ShopForMap，不成功跳过
    if ((point as DinersForMap).shopId === undefined) continue
    const _point: DinersForMap = point as DinersForMap
    customMarker.value.push({
      latitude: _point.latitude!,
      longitude: _point.longitude!,
      iconPath: '/static/image/planning/user.svg',
      label: {
        content: `送${
          _point.codes === undefined
            ? `#${_point.code}`
            : _point.codes.reduce((_sum, _curr) => (_sum += `#${_curr}`), '')
        }`,
        textAlign: 'center'
      },
      callout: {
        content: `${_point.consigneeName}`,
        display: 'ALWAYS',
        textAlign: 'center',
        bgColor: '#24c874',
        padding: '2px'
      }
    })
  }
  // 添加骑手坐标
  customMarker.value.push({
    latitude: riderGeo.latitude!,
    longitude: riderGeo.longitude!,
    iconPath: '/static/image/planning/rider-icon.svg'
  })
  // 起点坐标
  const startPoint = riderGeo
  // 终点坐标
  const endPoi = points.pop()

  // 构建起点、途经、终点坐标数据
  mapData.value.startPoi = `${startPoint?.longitude},${startPoint?.latitude}`
  mapData.value.endPoi = endPoi ? `${endPoi?.longitude},${endPoi?.latitude}` : ''
  mapData.value.wayPoi = points.reduce(
    (accumulator, currentValue) => (accumulator += `${currentValue?.longitude},${currentValue?.latitude};`),
    ''
  )
})
</script>

<style scoped></style>
